package cn.tedu.sp06.filter;

import cn.tedu.sp01.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型，pre前置，routing 运行 post后置，error错误
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;//前置过滤器
    }

    //过滤器顺序号
    @Override
    public int filterOrder() {
        return 6;//放在第6位
    }

    //针对当前请求，是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        //调用item-service需要判断权限

        //否则，不判断权限，直接跳过过滤代码

        //获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文对象获得调用的服务id
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);//("serviceId)
        //如果服务id是 item-service，返回true，否则返回false
        return "item-service".equalsIgnoreCase(serviceId);//IgnoreCase忽略大小写

    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        // http://localhost:3001/order-service/order123456?token=fdshnkj
        //获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文获得request对象
        HttpServletRequest request = ctx.getRequest();
        //从request取出token参数
        String token = request.getParameter("token");
        //如果没有token,null,""
        if (StringUtils.isBlank(token)) {
            //阻止继续调用
            ctx.setSendZuulResponse(false);
            //直接向客户端返回响应
            String json = JsonResult.build().code(400).msg("未登录").toString();
            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        return null;
    }
}
